package com.lianbi.pageStatic;

import com.lianbi.dao.TaskWorkDao;
import com.lianbi.util.ConfigUtil;
import com.mongodb.BasicDBObject;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

import java.io.*;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 传输存储控制类
 * 
 * @author You Jing
 * @version 1.0
 */
public class TransferManager {

	private int pageCount = 0;    //总页数
	private int lineNumber = 5;   //每页行数

	static TransferManager instance;

	/**
	 * 构造函数
	 */
	TransferManager() {
		super();
	}

	/**
	 * 获得传输存储控制类实例
	 * 
	 * @return　传输存储控制类实例
	 */
	public static TransferManager getInstance() {
		if (instance == null) {
			createNewInstance();
		}

		return instance;
	}

	/**
	 * 获得传输存储控制类实例 这是一个静态的同步方法，只生成一个实例
	 */
	private static synchronized void createNewInstance() {
		if (instance == null)
			instance = new TransferManager();
		
	}

	/**
	 * 处理所有业务
	 * 
	 */
	public void processTasks() {
		
		TaskWorkDao taskWorkDao = new TaskWorkDao();
		taskWorkDao.initPool();
		System.out.println(new Date());
		
		lineNumber = Integer.parseInt(ConfigUtil.getValue("lineNumber"));
		
		String str = ConfigUtil.getValue("str");
		String[] type = str.split(";");
		String[] name = {};
		for(int i = 0; i < type.length; i++){
			name = type[i].split(",");
			this.work(taskWorkDao, name);
		}
		
		//关闭数据库连接
        taskWorkDao.close();

	}
	
	public void work(TaskWorkDao taskWorkDao, String[] str) {
		
		String type = str[0];
		String nameList = str[1];
		String nameDetail = str[2];
		String outPath = str[3];
		String showUrl = str[4];
		List<BasicDBObject> signTypeList = taskWorkDao.getSignTypeList("1",""); //查询资讯类别
		BasicDBObject object = new BasicDBObject();
		object.put("lbbqId","");
		object.put("lbbqName","全部");
		signTypeList.add(0,object);
		List<BasicDBObject> lbbqList = taskWorkDao.getSignTypeList("2","RM"); //查询标签类别
		List<BasicDBObject> frientLinkList = taskWorkDao.getFrientLinkList("1"); //查询友情链接
		// 根据资讯类别生成html
		for(int j=0;j<signTypeList.size();j++) {
			String signTypeId = signTypeList.get(j).getString("lbbqId");
			String signTypeName = signTypeList.get(j).getString("lbbqName");
			int count = taskWorkDao.getCountBySign(type,signTypeId); //查询总条数
			pageCount = 0;            //重置起始页
			if(count > lineNumber) {  //大于每页行数，页数计算
				pageCount = count/lineNumber;
				int rem = count%lineNumber;
				if(rem != 0) {
					pageCount = ++pageCount;
				}
			}else { //小于每页行数，页数计算
				pageCount = ++pageCount;
			}

			List<BasicDBObject> list = null;
			for(int i = 1; i <= pageCount; i++) {
				//查询文章列表
				list = taskWorkDao.getListBySign(type,signTypeId,lineNumber*(i-1)+1, lineNumber*i);
				//生成静态化列表页面
				this.outListToHtml(list,signTypeList,lbbqList,frientLinkList,signTypeId,signTypeName, i, nameList,nameDetail, outPath, showUrl);
				//生成静态化内容页面
				this.initOutContentToHtml(list, signTypeList,lbbqList,frientLinkList,nameDetail,nameList, outPath, showUrl);
			}
		}
		// 根据标签生成html
		for(int k=0;k<lbbqList.size();k++) {
			String labelId = lbbqList.get(k).getString("lbbqId");
			int count = taskWorkDao.getCountByLabel(type,labelId); //查询总条数
			pageCount = 0;            //重置起始页
			if(count > lineNumber) {  //大于每页行数，页数计算
				pageCount = count/lineNumber;
				int rem = count%lineNumber;
				if(rem != 0) {
					pageCount = ++pageCount;
				}
			}else { //小于每页行数，页数计算
				pageCount = ++pageCount;
			}

			List<BasicDBObject> list = null;
			for(int i = 1; i <= pageCount; i++) {
				//查询文章列表
				list = taskWorkDao.getListByLabel(type,labelId,lineNumber*(i-1)+1, lineNumber*i);
				//生成静态化列表页面
				this.outListToHtml(list,signTypeList,lbbqList,frientLinkList,labelId,"全部", i, nameList,nameDetail, outPath, showUrl);
			}
		}
	}

	/**
	 * 生成静态化列表页面
	 * 
	 * @param list   单页list列表
	 * @param i      第几页
	 * 
	 * */
	public void outListToHtml(List<BasicDBObject> list,List<BasicDBObject> signTypeList,List<BasicDBObject> lbbqList,
							  List<BasicDBObject> frientLinkList,String signTypeId, String signTypeName,
							  int i, String name,String nameDetail, String outPath, String showUrl) {
		// 获取订单列表信息
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("afficheList", list);
		map.put("signTypeList", signTypeList);
		map.put("lbbqList", lbbqList);
		map.put("frientLinkList", frientLinkList);
		map.put("signType", signTypeId);
		map.put("pageCount", pageCount);
		map.put("url", ConfigUtil.getValue("url"));
		map.put("urls", ConfigUtil.getValue("urls"));
		map.put("showUrl", showUrl);
		map.put("name", name);
		map.put("nameDetail", nameDetail);
		map.put("signTypeName", signTypeName);
		map.put("nowPage", i);
		map.put("informationUrl", ConfigUtil.getValue("informationUrl"));
		
		Configuration cfg = new Configuration();
		//通过userID获取user信息
		String path = TaskScheduler.class.getClassLoader().getResource("").toString();
		path = path.substring(6, path.length());
		Writer out=null;
		try {
			//URL fileURL=this.getClass().getResource("/resource/res.txt");
			cfg.setDirectoryForTemplateLoading(new File(this.getClass().getResource("/ftl").getFile()));
//			cfg.setDirectoryForTemplateLoading(new File(path+"ftl/"));  //设置读取模板文件的目录
			Template t = cfg.getTemplate(name+".ftl");  //读取文件名为Test.ftl的模板
			out = new OutputStreamWriter(new FileOutputStream(outPath+name+signTypeId+i+".html"), "utf-8");  //输出流
			t.process(map, out); //动态加载root中的数据到Test.html。数据在模板中定义好了。
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (TemplateException e) {
			e.printStackTrace();
		}finally{
			try {
				out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
 
	}
	
	/**
	 * 初始化内容页静态化
	 * 
	 * @param list   单页list列表
	 * 
	 * */
	public void initOutContentToHtml(List<BasicDBObject> list,List<BasicDBObject> signTypeList, List<BasicDBObject> lbbqList,
									 List<BasicDBObject> frientLinkList,String name,String nameList, String outPath, String showUrl) {
		
		if(list != null && list.size() > 0) {
			for(BasicDBObject dataObject : list) {
				//生成详细内容也html
				this.outContentToHtml(dataObject,signTypeList,lbbqList,frientLinkList, name,nameList, outPath,showUrl);
			}
		}
	}
	
	/**
	 * 生成静态化详细内容页面html
	 * 
	 * @param dataObject  内容详情object
	 * 
	 * */
	public void outContentToHtml(BasicDBObject dataObject, List<BasicDBObject> signTypeList, List<BasicDBObject> lbbqList,
								 List<BasicDBObject> frientLinkList, String name,String nameList, String outPath, String showUrl) {
		TaskWorkDao taskWorkDao = new TaskWorkDao();

		// 获取订单列表信息
		Map<String,Object> map = new HashMap<String,Object>();
		if(null == dataObject.getString("label") || "".equals(dataObject.getString("label"))) {
			map.put("labelList", "");
		} else {
			List<BasicDBObject> labelList = taskWorkDao.getLabelList(dataObject.getString("label")); //根据资讯id获取标签
			map.put("labelList", labelList);
		}
		map.put("dataObject", dataObject);
		map.put("signTypeList", signTypeList);
		map.put("lbbqList", lbbqList);
		map.put("frientLinkList", frientLinkList);

		map.put("urls", ConfigUtil.getValue("urls"));
		map.put("showUrl", showUrl);
		map.put("informationUrl", ConfigUtil.getValue("informationUrl"));
		map.put("nameList", nameList);

		Configuration cfg = new Configuration();
		//通过userID获取user信息
		String path = TaskScheduler.class.getClassLoader().getResource("").toString();
		path = path.substring(6, path.length());
		Writer out=null;
		try {
			cfg.setDirectoryForTemplateLoading(new File(this.getClass().getResource("/ftl").getFile()));  //设置读取模板文件的目录
			Template t = cfg.getTemplate(name+".ftl");  //读取文件名为Test.ftl的模板
			 out = new OutputStreamWriter(new FileOutputStream(outPath+name+dataObject.getString("id")+".html"), "utf-8");  //输出流
			t.process(map, out); //动态加载root中的数据到Test.html。数据在模板中定义好了。
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (TemplateException e) {
			e.printStackTrace();
		} finally{
			try {
				out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	public static void main(String[] args) {
		String str = ConfigUtil.getValue("str");
		String[] type = str.split(";");
		String[] name = {};
		for(int i = 0; i < type.length; i++){
			System.out.println(type[i]);
			name = type[i].split(",");
			System.out.println(name[0]);
			System.out.println(name[1]);
			System.out.println(name[2]);
		}
		
//		for(int i = 0; i < str.length; i++) {
//			System.out.println(str[i][0]);
//			System.out.println(str[i][1]);
//			System.out.println(str[i][2]);
//		}
//		JSONArray jsonArray = JSONArray.fromObject(str);
//		System.out.println(jsonArray.size());
	}
}
